'''
Created on Feb 10, 2010

@author: christianp
'''
import Queue
import copy
import threading, time

class TileSeeder(threading.Thread):

    __lock = threading.Lock()
    
    #__tile_seeds = []
    __activeSeedsQue = []
    
    __gaugeTiles = None
    __labelTilesToBeDone = None
    __stxtGaugeDone = None
    __labelTilesFailed = None
    __stxtGaugeRemaining = None
    
    __seedQueue = Queue.Queue()
    
    __selectedSeed = None
    
    in_process = False
    
    __quit = False
    
    def __init__(self):
        threading.Thread.__init__(self, name="TileSeeder")

    def GetQue(self):
        return self.__seedQueue
    
    def SetLabels(self, gaugeTiles, stxtGaugeDone, stxtGaugeRemaining, labelTilesToBeDone, labelTilesFailed):
        self.__gaugeTiles = gaugeTiles
        self.__labelTilesToBeDone = labelTilesToBeDone
        self.__labelTilesFailed = labelTilesFailed
        self.__stxtGaugeDone = stxtGaugeDone
        self.__stxtGaugeRemaining = stxtGaugeRemaining
            
    def UpdateLabels(self, values):
        self.__lock.acquire()
        try:
            self.__labelTilesFailed.SetValue("Tiles failed: "+str(values[1]))
            self.__gaugeTiles.SetValue(values[2])
            self.__stxtGaugeDone.SetLabel(str(values[3]))
            
            tiles_remaining = values[4] - values[3]
            
            self.__stxtGaugeRemaining.SetLabel(str(tiles_remaining))
            self.__labelTilesToBeDone.SetValue("Total nr of tiles: "+str(str(values[4])))
        finally:
            self.__lock.release()
    
    def run(self):
        update_que = None
        while self.in_process:
            if not(self.__seedQueue.empty()):
                iSeedValues = self.__seedQueue.get()
                seed = iSeedValues[0]
                quitseed = iSeedValues[1]
                
                self.AddActiveSeed(seed)
                aSeedvalues = self.FetchActiveSeedQueue(seed.tile_schema.name)
                
                if not(quitseed):
                    update_que = aSeedvalues[1]
                    if not update_que is None and not update_que.empty():
                        while not update_que.empty():
                            update_que.get()
                    
                    if seed.active and not seed.isAlive():
                        seed.start()
                    else:
                        values = [seed.tile_schema.name, seed.tilesfailed, 0, seed.tilesdone, seed.totaltiles]
                        self.UpdateLabels(values)
                else:
                    quit = self.Quit(seed, iSeedValues[2], aSeedvalues[2])
                    if quit:
                        terminate = iSeedValues[3]
                        if terminate:
                            print("TileSeeder: Quit")
                            return
                    
            if not quitseed:
                if not update_que is None and not update_que.empty():
                    values = update_que.get()
                    if seed.tile_schema.name == values[0]:
                        self.UpdateLabels(values)
                    
            time.sleep(0.1)
    
    def Quit(self, seed, name, que):
        if (seed.tile_schema.name == name):
            quit_que = copy.copy(que)
            quit_que.put(True)
            self.RemoveActiveSeed(seed)
            return True
        else:
            return False
    
    def RemoveActiveSeed(self, seed):
        for i in range(0, len(self.__activeSeedsQue)):
            values = self.__activeSeedsQue[i]
            if (values[0] == seed.tile_schema.name):
                self.__activeSeedsQue.pop(i)
                return
                #del(self.__activeSeedsQue[i])
    
    def ContainsActiveSeed(self, seed):
        for values in self.__activeSeedsQue:
                if (values[0] == seed.tile_schema.name):
                    return True

        return False

    def FetchActiveSeedQueue(self, name):
        for values in self.__activeSeedsQue:
            if (values[0] == name):
                return values

        return None
    
    def AddActiveSeed(self,seed):
        self.__lock.acquire()
        try:
            if not self.ContainsActiveSeed(seed):
                quitQue = seed.GetQuitQueue()
                updateQue = seed.GetUpdateQueue()
                name = seed.tile_schema.name
                
                values = [name, updateQue, quitQue]
                
                self.__activeSeedsQue.append(values)
                print("TileSeeder: Add new TileSeed")
        finally:
            self.__lock.release()
   
    def QuitTileSeed(self, seed):
        seed = self.FetchTileSeed(seed.tile_schema.name)
        que = seed.GetQuitQueue()
        que.put(True)
         
    def ProccessTileSeeds(self):
        for tile_seed in self.tile_seeds:
            tile_seed.findUnderlayingLevels()
    
    def _print(self, prefix):
        print(prefix + " TileSeeder")